package com.jediflasher.game_server.database;

import com.jediflasher.game_server.util.log.Logger;

import java.sql.*;
import java.util.Arrays;

/**
 * User: Obi
 * Date: 24.05.11
 * Time: 23:11
 */
class DataBaseConnection {

	private static final String dbUrl = "jdbc:postgresql://localhost:5432/";
	private static final String dbName = "game";
	private static final String dbUser = "postgres";
	private static final String dbPassword = "wardragon";

	public DataBaseConnection() {
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException exception) {
			Logger.logError("Couldn't find the driver!");
			Logger.logError(exception.getMessage());
			System.exit(1);
		}

		Connection c = null;

		try {
			c = DriverManager.getConnection(dbUrl + dbName, dbUser, dbPassword);
		} catch (SQLException se) {
			Logger.logError("Couldn't connect: print out a stack trace and exit.");
			Logger.logError(se.getMessage());
			System.exit(1);
		}

		if (c != null)
			Logger.log("Database connect complete!");
		else
			Logger.logError("Database connect failed");

		try {
			assert c != null;
			_statement = c.createStatement();
		}catch (Exception exception) {
			Logger.logError(exception.getMessage());
		}
	}

	private Statement _statement;

	private ResultSet _resultSet;

	public ResultSet executeQuery(String query) {
		ResultSet rs = null;
		try {
			rs = _statement.executeQuery(query);
		} catch (SQLException e) {
			Logger.logError(e.getMessage());
			Logger.logError(Arrays.toString(e.getStackTrace()));
		}

		return rs;
	}

	public Boolean addUser(String name, String password, String email) {
		try {
			_resultSet = _statement.executeQuery("SELECT * FROM users WHERE name='"+name+"'");
			if(_resultSet.next()) {
				Logger.logWarning("User with name " + name + " already created");
				return false;
			}

			String values = "'"+name +"','"+password+"','"+email + "'";
			_statement.execute(
					"INSERT INTO users (name, password, email) " +
							"VALUES (" + values + ")");
			return true;

		} catch (SQLException e) {
			Logger.log("Registration error:\n" + e.getMessage());
			return false;
		}
	}

	private ResultSet getUserBy(String fieldName, Object fieldValue) throws SQLException {
		String query = "SELECT * FROM users WHERE "+fieldName+"='"+fieldValue+"'";
		return _statement.executeQuery(query);
	}
}
